#ifndef  __SELECT_SVR_H__
#define __SELECT_SVR_H__

#include <iostream>
#include <string>
#include <sys/select.h>
#include <sys/time.h>
#include "Log.hpp"
#include "Sock.hpp"

#define BITS 8
#define NUM (sizeof(fd_set)*BITS)
#define FD_NONE -1

using namespace std;
class SelectServer
{
public:
    SelectServer(const uint16_t &port = 8080):_port(port)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock,_port);
        Sock::Listen(_listensock);
        logMessage(DEBUG,"create base socket sucess");
        for(int i = 0;i< NUM;i++) _fd_array[i] = FD_NONE;
        //规定_fd_array[0] = listensock
        _fd_array[0] = _listensock;
    }

    void Start()
    {
        while (true)
        {
            //struct timeval timeout = {1,0};
            //FD_SET(_listensock,&rfds);//将_listensock添加到文件描述符集


            //int n = select(_listensock+1,&rfds,nullptr,nullptr,&timeout);
            DebugPrint();
            fd_set rfds;
            FD_ZERO(&rfds);//清空文件描述符集
            int maxfd = _listensock;
            for(int i = 0;i<NUM;i++)
            {
                if(_fd_array[i] == FD_NONE) continue;
                FD_SET(_fd_array[i],&rfds);
                if(maxfd < _fd_array[i]) maxfd = _fd_array[i];
            }

            int n = select(maxfd+1,&rfds,nullptr,nullptr,nullptr);//阻塞等待
            switch (n)
            {
            case 0:
                logMessage(DEBUG,"time out...");
                break;
            case -1:
                logMessage(DEBUG,"select error : %d : %s",errno,strerror(errno));
                break;
            default:
                logMessage(DEBUG,"get a new link event...");
                HandlerEvent(rfds);
                break;
            }
        }
        
    }

    ~SelectServer()
    {
        if(_listensock >=0) close(_listensock);
    }
private:
    void HandlerEvent(const fd_set &rfds)//fd_set 是一个集合
    {
        for(int i = 0;i<NUM;i++)
        {
            if(_fd_array[i] == FD_NONE) continue;
            if(FD_ISSET(_fd_array[i],&rfds))
            {
                if(_fd_array[i] == _listensock)
                {
                    //读事件就绪：连接时间到来，accept
                    Accepter();
                }
                else
                {
                    Recver(i);
                }
            }
        }
    }
    void Recver(int pos)
    {
        //读事件就绪：IINPUT事件到来,recv,read
        logMessage(DEBUG,"message int,get IO event: %d",_fd_array[pos]);
        char buffer[1024];
        int n = recv(_fd_array[pos],buffer,sizeof(buffer)-1,0);
        if(n > 0)
        {
            buffer[n] = 0;
            logMessage(DEBUG,"client[%d]# %s",_fd_array[pos],buffer);
        }
        else if(n ==0)
        {
            logMessage(DEBUG,"client[%d] quit,me to..",_fd_array[pos]);
            close(_fd_array[pos]);
            _fd_array[pos] = FD_NONE;
        }else
        {
            logMessage(WARNING, "%d sock recv error, %d : %s", _fd_array[pos], errno, strerror(errno));
            close(_fd_array[pos]);
            _fd_array[pos] = FD_NONE;
        }
    }
    void Accepter()
    {
        string clientip;
        uint16_t clientport = 0;
        
        int sock = Sock::Accept(_listensock,&clientip,&clientport);
        if(sock < 0)
        {
            logMessage(WARNING,"accept error");
            return;
        }
        logMessage(DEBUG,"get a new line sucess : [%s:%d] : %d",clientip.c_str(),clientport,sock);
        int pos = 1;
        for(;pos < NUM;pos++)
        {
            if(_fd_array[pos] == FD_NONE) break;
        }
        if(pos == NUM)
        {
            logMessage(WARNING,"%s:%d","select server already full close: %d",sock);
            close(sock);
        }
        else{
            _fd_array[pos] = sock;
        }    
    }
    
    void DebugPrint()
    {
        cout << "_fd_arry[]: ";
        for(int i =0;i<NUM;i++)
        {
            if(_fd_array[i] == FD_NONE) continue;
            cout<< _fd_array[i]<<" ";
        }
        cout<<endl;
    }
private:
    uint16_t _port;
    int _listensock;
    int _fd_array[NUM];
};
#endif